package com.gzhryc.weixin.xcx;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;

import com.gzhryc.common.json.JsonTools;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.gzhryc.weixin.gzh.models.AccessToken;
import com.gzhryc.weixin.xcx.dto.GetQrcodeBRequest;
import com.gzhryc.weixin.xcx.exceptions.XcxErrorException;

public class XcxQrcodeApi {
	
	private final AccessToken accessToken;
	
	/**
	 * 初始化微信支付API
	 */
	public XcxQrcodeApi(AccessToken accessToken){
		this.accessToken = accessToken;
	}

	/**
	 * 获取小程序码，无限
	 * @param apiReq
	 * @throws XcxErrorException
	 */
	public boolean getQrcodeB(GetQrcodeBRequest apiReq,String filePath){
		CloseableHttpResponse response = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			URI uri = new URIBuilder()
		        .setScheme("https")
		        .setHost("api.weixin.qq.com")
		        .setPath("/wxa/getwxacodeunlimit")
		        .setParameter("access_token",accessToken.getAccess_token())
		        .build();
			
			HttpPost httpPost = new HttpPost(uri);
			
			StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq),
			        ContentType.create("application/json", Consts.UTF_8));
			httpPost.setEntity(strEntity);
			/*
			//装填参数
	        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
	        nvps.add(new BasicNameValuePair("page",apiReq.getPage()));
	        nvps.add(new BasicNameValuePair("scene",apiReq.getScene()));
	        if(apiReq.getWidth() != null){
	        	nvps.add(new BasicNameValuePair("width",apiReq.getWidth().toString()));
	        }else{
	        	nvps.add(new BasicNameValuePair("width","430"));
	        }
	        if(apiReq.getAuto_color() != null){
	        	nvps.add(new BasicNameValuePair("auto_color",apiReq.getAuto_color().toString()));
	        }else{
	        	nvps.add(new BasicNameValuePair("auto_color","false"));
	        }
	        if(apiReq.getLine_color() != null){
	        	nvps.add(new BasicNameValuePair("line_color",JsonTools.toJson(apiReq.getLine_color())));
	        }else{
	        	nvps.add(new BasicNameValuePair("line_color","{\"r\":\"0\",\"g\":\"0\",\"b\":\"0\"}"));
	        }
	        if(apiReq.getIs_hyaline() != null){
	        	nvps.add(new BasicNameValuePair("is_hyaline",apiReq.getIs_hyaline().toString()));
	        }else{
	        	nvps.add(new BasicNameValuePair("is_hyaline","false"));
	        }
	        //设置参数到请求对象中
	        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
	       	*/
			response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if(entity != null){
				byte[] byteArray = EntityUtils.toByteArray(entity);
				
				String str = new String(byteArray,"UTF-8");
				if(XcxErrorException.isErrorResponse(str)){
					System.out.println("获取小程序二维码错误响应："+str);
				}else{
					File file = new File(filePath);
					if(!file.exists()){
						file.getParentFile().mkdirs();
						file.createNewFile();
					}
					OutputStream out = null;
					try{
						out = new FileOutputStream(file);
						out.write(byteArray);
					} finally {
						if(out != null){
							out.close();
						}
					}
					return true;
				}
			}
		} catch(Exception e){
			//throw new XcxErrorException(e.getCause());
			e.printStackTrace();
		} finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return false;
	}
}
